<template>
	<view>
		<!-- 	显示暂无消息 -->
		<view v-show="usersList.length === 0" class="no-messages">暂无消息</view>
		<uni-list :border="true">
			<!-- 右侧带角标 -->
			<uni-list-chat v-for="user in usersList" :key="user.fromUser" :avatar-circle="true" :title="user.fromUser"
				:avatar="avatarList[user.fromUser]" :note="user.text" :time="new Date(user.time).toTimeString().slice(0, 5)"
				:badge-text="user.unReadCount"		 
				@click="toMsgPage(user.fromUser)"
				:clickable='true'
				>
			</uni-list-chat>
		</uni-list>
		<!-- 	<tab-bar :current="4"></tab-bar> -->
	</view>
</template>

<script>
	import request from '@/util/request';
	export default {
		data() {
			return {
				loginUserId: '',
				recipientID: '',
				usersList: [],
				avatarList: {},
				avatarUrl1: '', //登陆者头像
				users: [],
				socketOpen: false,
				isChatDataStored: false,
				allChatData: {},
				isAsyncDataUpdateInProgress: false,
				lastHeartbeatTime: 0, // 记录最后一次接收到心跳包的时间
				heartbeatCheckInterval: null, // 存储心跳检查定时器的引用
				reconnectAttempts: 0, // 新增一个重连尝试次数的计数器
				maxReconnectAttempts: 5, // 最大重连次数
				heartbeatInterval: 30000, // 心跳包发送间隔，单位：毫秒
				heartbeatTimer: null, // 心跳包定时器
				avatarUrl: '',
				isMerchant: false, // 是否是商家
				isMerchantPhone: '',
				loginUserId:'',//商家手机号
				wb:"wss://absolutuniq.com:8088/imserver",
				avatar:'../../static/icon/默认头像.jpg',//用户头像
			};
		},
		// onShow() {
		// 	//debugger
		// 	// this.loginUserId = loginUserId.loginUserId;
		// 	// this.avatarUrl1 = loginUserId.avatarUrl;
		// 	// this.connectWebSocket();
		// },
		onShow() {
			// this.loginUserId = loginUserId.loginUserId;
			// this.avatarUrl1 = loginUserId.avatarUrl;
			 this.connectWebSocket();
		},
		onUnload() {
			//uni.closeSocket();
		},
		methods: {
			toMsgPage(fromUser){
				let avatar = this.avatarList[fromUser]
				uni.closeSocket();
				uni.navigateTo({
					url: '/pages/service/index?fromUser='+fromUser+'&avatar='+avatar,
				});
				
			},
			uniqueUsersList() {
				const allMessages = this.usersList;
				const uniqueUsers = {};
				allMessages.forEach(message => {
					if (!uniqueUsers[message.fromUser] || message.sendTime > uniqueUsers[message.fromUser]
						.sendTime ||
						(message.sendTime === uniqueUsers[message.fromUser].sendTime && message.id > uniqueUsers[
							message.fromUser].id)) {
						uniqueUsers[message.fromUser] = message;
					}
				});
				this.users = Object.values(uniqueUsers);
			},
			connectWebSocket(loginUserId) {
				// 开始连接
				let loginUser = uni.getStorageSync("loginUser")
				uni.connectSocket({
					url: this.$wbBaseUrl + '/'+loginUser.phone+'_readList/list',
					startTime: Date.now()

				});
				uni.onSocketOpen((res) => { // 使用箭头函数
					this.socketOpen = true;
					console.log('WebSocket连接成功！' + this.socketOpen);
				//	this.startHeartbeat(); // 发送心跳包
					console.log('WebSocket连接成功！');
					this.reconnectAttempts = 0; // 重置重连次数
				});
				uni.onSocketClose(() => {
				//	this.stopHeartbeat();
					console.log('WebSocket连接已关闭，准备重连...');
					this.reconnectWebSocket(); // 重连WebSocket
					// location.reload();
				});

				uni.onSocketError(() => {
				//	this.stopHeartbeat();
					console.log('WebSocket连接发生错误，准备重连...');
					this.reconnectWebSocket(); // 重连WebSocket
					// location.reload();
				});
				// 查询本地数据
				let localUsersList = uni.getStorageSync("usersList");
				if (localUsersList) {
					localUsersList.map(item => {
						item.unReadCount = 0; // 重置未读计数
						this.IsLogin(item.fromUser)
					});
					this.usersList = localUsersList;
					console.log(this.usersList)
				}
				uni.onSocketMessage((res) => {
					// 处理心跳消息
					if (res.data === 'heartbeat') {
						this.lastHeartbeatTime = Date.now(); // 更新最后一次接收到心跳包的时间
						console.log("收到心跳包");
						// 可以在这里做一些心跳包的处理，例如重置计时器等
						return;
					}
					debugger
					// 接收服务器内容
					try {
						const parsedData = JSON.parse(res.data);
						const message = JSON.parse(res.data);
						if (parsedData.readUnLineMsg) {
							Object.keys(parsedData.readUnLineMsg).forEach(userId => {
								const messages = parsedData.readUnLineMsg[userId];

								messages.forEach(msg => {
									if (msg.recall) {
										this.handleMessage(msg);
									} else {
										this.readUnLineMsg(parsedData.readUnLineMsg);
									}
								});
								
							});
						}
					} catch (e) {
						console.error('解析服务器消息失败：', e);
					}
				});

			},
			// 检查心跳包是否超时
			checkHeartbeatTimeout() {
				const HEARTBEAT_TIMEOUT = 60 * 1000; // 心跳超时时间，这里设置为60秒
				if (Date.now() - this.lastHeartbeatTime > HEARTBEAT_TIMEOUT) {
					console.log('心跳包超时，准备重连...');
					let rec = '心跳包超时，准备重连...'
					this.reconnectWebSocket(rec); // 触发重连逻辑

				}
			},
			// 开始检查心跳包
			startHeartbeatCheck() {
				this.heartbeatCheckInterval = setInterval(() => {
					console.log('正在检查心跳包');
					this.checkHeartbeatTimeout();
				}, 60000); // 每60秒检查一次心跳包是否超时
			},
			// 开始发送心跳包
			startHeartbeat() {

				if (!this.heartbeatTimer) {
					this.heartbeatTimer = setInterval(() => {
						if (this.socketOpen) {
							console.log('发送心跳包');
							uni.sendSocketMessage({
								data: 'heartbeat'
							});
						}

					}, this.heartbeatInterval);
				}
			},
			// 停止发送心跳包
			stopHeartbeat() {
				if (this.heartbeatTimer) {
					clearInterval(this.heartbeatTimer);
					this.heartbeatTimer = null;
				}
			},
			// 重连WebSocket
			reconnectWebSocket() {
				if (this.isReconnecting) {
					console.log('已经在重连中，忽略本次重连请求');
					return;
				}
				this.isReconnecting = true;
				const backoffTime = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000); // 最长 30秒重试间隔
				if (this.reconnectAttempts >= this.maxReconnectAttempts) {
					console.log('重连次数超过最大限制，停止重连');
					uni.showToast({
						title: '网络连接失败，请稍后刷新再试',
						icon: 'none'
					});
					this.saveSocketMsgQueueToLocal(); // 保存消息队列到本地存储
					// 达到最大重连次数后刷新页面
					setTimeout(() => {
						const currentPage = getCurrentPages().pop(); // 获取当前页面实例
						if (currentPage) {
							uni.reLaunch({
								url: currentPage.route // 重新加载当前页面
							});
						}
					}, backoffTime);
			
				} else {
			
					this.reconnectAttempts++;
					const delay = Math.min(5000 * Math.pow(2, this.reconnectAttempts - 1), 60000);
					const randomDelay = Math.random() * 1000;
					setTimeout(() => {
						// 连接WebSocket
						this.connectWebSocket();
						console.log('正在重连...');
						this.isReconnecting = false; // 重连操作发起后，重置标识
					}, delay + randomDelay);
				}
			},
			// 更新未读
			readUnLineMsg(unLineMsg) {
				debugger
				let localUsersList = uni.getStorageSync("usersList") || [];
				let unreadCountMap = {}; // 用于记录每个用户的未读消息计数
				for (const key in unLineMsg) {
					let msg = unLineMsg[key];
					let lastmsg = msg[msg.length - 1]; // 获取每组消息的最后一条
					let msgbody = {
						id: lastmsg.id,
						fromUser: lastmsg.fromUser,
						text: lastmsg.text || '语音', // 如果是语音消息就显示'语音'
						time: lastmsg.sendTime,
						unReadCount: msg.length > 99 ? '99+' : msg.length, // 如果未读消息数大于99，显示'99+'

					};
					const index = this.usersList.findIndex(item => item.fromUser === msgbody.fromUser);
					if (index > -1) {
						this.usersList.splice(index, 1); // 移除旧消息
					}
					this.usersList.push(msgbody); // 添加新消息
				}
				// 排序和存储更新后的列表
				this.usersList.sort((a, b) => new Date(b.time) - new Date(a.time));

				if (localUsersList.length > 0) {
					localUsersList.forEach(item => {
						item.unReadCount = 0; // 将未读计数重置为0
					});

					this.usersList.forEach(newMsg => {
						const index = localUsersList.findIndex(item => item.fromUser === newMsg.fromUser);
						if (index > -1) {
							localUsersList.splice(index, 1); // 移除旧用户
						}
						localUsersList.push(newMsg); // 添加新消息
					});

					localUsersList.sort((a, b) => new Date(b.time) - new Date(a.time));
					uni.setStorageSync("usersList", localUsersList);
					this.usersList = localUsersList; // 更新 this.usersList
				} else {
					uni.setStorageSync("usersList", this.usersList);
				}

			},
			handleMessage(msg) {

				if (msg.recall) {
					this.handleWithdrawNotification(msg);
				} else {
					const existingUser = this.usersList.find(u => u.fromUser === msg.fromUser && u.sendTime === msg
						.sendTime);
					if (!existingUser) {
						this.usersList.push({
							fromUser: msg.fromUser,
							text: msg.text,
							sendTime: msg.sendTime,
							lastMessage: msg.text,
							unreadCount: msg.unreadCount,
							isRead: false,
							id: msg.id || Date.now()
						});
					}
				}
			},
			// 处理撤回通知
			handleWithdrawNotification(message) {

				// 从本地存储中获取当前的用户消息列表
				let localUsersList = uni.getStorageSync("usersList");
				// 查找需要被撤回的消息的索引
				const index = this.usersList.findIndex(item => item.id === message.id);
				if (index !== -1) {
					this.usersList.splice(index, 1); // 删除该条消息
					const withdrawMessage = {
						text: message.fromUser === this.loginUserId ? '你撤回了一条消息' : '对方撤回了一条消息',
						fromUser: message.fromUser === this.loginUserId ? this.loginUserId : message.fromUser,
						type: 'withdraw',
						time: Date.now(),
						id: Date.now() // 新增消息ID属性
					};
					this.usersList.splice(index, 0, withdrawMessage);
					uni.setStorageSync("usersList", this.usersList);
					// this.saveChatDataToLocal(withdrawMessage);
					this.$forceUpdate(); // 强制更新视图
				} else {
					console.log('未找到消息，无法更新');
				}
			},
			sendMessage(messageContent) {
				if (this.isAsyncDataUpdateInProgress) {
					console.log('正在进行异步数据更新操作，暂不处理发送消息请求');
					return;
				}
				this.isAsyncDataUpdateInProgress = true;

				const message = {
					fromUser: this.loginUserId,
					text: messageContent,
					sendTime: new Date().getTime(),
					id: Date.now()
				};
				this.sendSocketMessage(message);
				this.usersList.push(message);

				this.$nextTick(() => {
					this.$forceUpdate();
					this.$forceUpdate('uniqueUsersList');
				});

				const sendMessageStartTime = Date.now();

				Promise.all([this.sendSocketMessage(message), this.saveChatDataToLocal(message)])
					.then(() => {
						const sendMessageEndTime = Date.now();
						console.log('发送消息操作完成，开始时间：', sendMessageStartTime, '结束时间：', sendMessageEndTime);
						this.isAsyncDataUpdateInProgress = false;
					})
					.catch((err) => {
						console.error('发送消息过程中出现错误：', err);
						this.isAsyncDataUpdateInProgress = false;
					});
			},
			sendSocketMessage(message) {
				if (this.socketOpen) {
					uni.sendSocketMessage({
						data: JSON.stringify(message)
					});
				} else {
					console.error('WebSocket未连接，无法发送消息');
				}
			},

			withdrawMessage(messageId) {
				const index = this.usersList.findIndex(item => item.id === messageId);
				if (index !== -1) {
					const item = this.usersList[index];
					if (this.isWithdrawable(item.sendTime)) {
						this.sendWithdrawMessageToServer(messageId);
					} else {
						uni.showToast({
							title: '消息已经发送超过两分钟，不可撤回',
							icon: 'none'
						});
					}
				}
			},
			// 获取对面的头像
			IsLogin(userId) {
				request({
					url: '/users/getUserAvatarUrl',
					method: 'get',
					data: {
						userId: userId
					}
				}).then(res => {
					if(res.msg){
						 this.avatarList[userId] = this.$baseUrl + res.msg;
					}else{
						 this.avatarList[userId] = this.avatar;
					}
					 // 触发视图更新，通知使用该头像的地方重新渲染（如果需要）
				}).catch(err => {
					console.error('获取用户信息失败：', err);
					// 可以根据具体情况进行更合适的错误处理，比如设置默认值、提示用户等
				});
			},
			sendWithdrawMessageToServer(messageId) {
				const withdrawMessage = {
					type: 'withdraw',
					messageId: messageId
				};
				this.sendSocketMessage(withdrawMessage);
			},
			isWithdrawable(sendTime) {
				const currentTime = Date.now();
				return currentTime - sendTime <= 120 * 1000; // 2分钟内可撤回
			}
		},
		beforeDestroy() {
			clearInterval(this.heartbeatCheckInterval); // 清除心跳检查定时器

		},
	};
</script>

<style>
	.no-messages {
		text-align: center;
		color: #888;
		font-size: 20px;
		/* 设置字体大小为30px */
	}

	.container {
		display: flex;
		flex-direction: column;
	}

	.has-unread::after {
		content: '';
		position: absolute;
		top: 0;
		right: 0;
		width: 10px;
		height: 10px;
		background-color: red;
		border-radius: 50%;
	}

	.message-item {
		display: flex;
		align-items: center;
		padding: 10px;
		border-bottom: 1px solid #e0e0;
	}

	.avatar {
		width: 36px;
		height: 36px;
		background-color: 0;
		border-radius: 50%;
		background-size: cover;
		background-position: center;
		marginRight: 10px;
	}

	.message-content {
		flex: 1;
		display: flex;
		flex-direction: columns;
	}

	.name {
		font-weight: bold;
	}

	.text {
		marginTop: 5px;
	}

	.time {
		marginTop: 5px;
		color: 888;
	}
</style>